﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using Ornament.Messages;
using Ornament.Messages.Dao;
using Ornament.Web;
using Ornament.Web.Mvc;

namespace Ornament.MVCWebFrame.Controllers
{
    [NHibernateFilter]
    public class MessagesController : Controller
    {
        public ActionResult Works(int pageSize, int pageIndex, string template, ReadStatus? readState)
        {
            IList<Info> infos = GetWorks(pageSize, pageIndex, template, readState);
            return View(infos);
        }

        public ActionResult ListWorks(int pageSize, int pageIndex, string template, ReadStatus? readState)
        {
            IList<Info> infos = GetWorks(pageSize, pageIndex, template, readState);
            var result = infos.Select(info => info.Show(template)).ToList();
            return Json(result);
        }

        public ActionResult Logs()
        {
            return View();
        }

        public ActionResult ReadIt(Guid? id)
        {
            try
            {
                OrnamentContext.Current.GetDaoFactory<InfoManager>().SetReadState(ReadStatus.Read, id.Value,
                                                                    OrnamentContext.Current.CurrentUser);
                return Json(new ReturnResult("成功保存", true));
            }
            catch (Exception ex)
            {
                return Json(new ReturnResult(ex, true), JsonRequestBehavior.AllowGet);
            }
        }

        private static IList<Info> GetWorks(int pageSize, int pageIndex, string template, ReadStatus? readState)
        {
            var searcher = new InfoSearcher
                               {
                                   PageSize = pageSize,
                                   PageIndex = pageIndex,
                                   ReadStatus = readState ?? ReadStatus.UnRead,
                                   RelivateUser = OrnamentContext.Current.CurrentUser,
                                   TypeNames = new[] { "WorkList" }
                               };

            IInfoDao dao = OrnamentContext.Current.GetDaoFactory<InfoManager>().Factory.InfoDao;
            return dao.Find(searcher);
        }
    }
}